<?php
namespace admin\action;

use herosphp\bean\Beans;
use herosphp\exception\UnSupportedOperationException;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;

/**
 * product_type action
 * @package admin\action
 * @author yangjian<yangjian102621@gmail.com>
 */
class ProductTypeAction extends CommonAction {

    protected $serviceBean = 'product.productType.service';
    protected $actionTitle = '产品分类';

    //数据列表页面
    public function index( HttpRequest $request ) {

        $name = $request->getParameter('name', 'trim');
        $status = $request->getParameter('status', 'trim');

        if ( $status === '' ) {
            $status = '-1';
            $request->addParameter('status', '-1');
        }
        $conditions = array();
        if ( $name ) $conditions['name'] = "%{$name}%";
        if ( $status != '-1' ) $conditions['status'] = $status;

        $this->setConditions($conditions);
        $this->loadTypes();
        $this->assign('tableHeader', array('名称','上级分类','下级种类数','当前状态'));
        if ( $request->getParameter('__export') == 1 ) { //导出数据
            $this->export($request);

        } else { //加载模板
            parent::index($request);
            $this->setView('product/type_index');
            $this->assign("title", $this->actionTitle."列表");
            $this->assign('breadcrumb', array('产品管理',$this->getTemplateVar('title')));
            $this->assign('breadUrl', array('javascript:;','javascript:;'));
        }

    }

    //加载分类
    public function loadTypes() {
        $service = Beans::get($this->getServiceBean());
        $types = $service->getItems(array('status' => 1));
        $this->assign('ftypes', $types);
    }

    //数据添加页面
    public function add(HttpRequest $request) {
        throw new UnSupportedOperationException('暂时不支持该操作.');
    }

    //数据编辑页面
    public function edit(HttpRequest $request) {
        $id = $request->getParameter('id', 'intval');
        if ( $id <= 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        $item = $service->getItem($id);
        if ( empty($item) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, null, $item);
    }

    //插入数据操作
    public function insert(HttpRequest $request) {

        $data = $request->getParameter('data');
        //build idpath
        $service = Beans::get($this->serviceBean);
        $parentType = $service->getItem($data['pid']);
        $data['idpath'] = "{$parentType['idpath']},{$data['pid']}";
        parent::__insert($data);
    }

    //更新数据操作
    public function update(HttpRequest $request) {

        $data = $request->getParameter('data');
        $id = $request->getParameter('id', 'intval');
        //build idpath
        $service = Beans::get($this->serviceBean);
        $parentType = $service->getItem($data['pid']);
        $data['idpath'] = "{$parentType['idpath']},{$data['pid']}";
        parent::__update($data, $id);

    }

    //启用，禁用分类
    public function set(HttpRequest $request) {
        $value = $request->getParameter('value', 'trim');
        $id = $request->getParameter('id', 'trim');
        if ( $value == 0 ) {
            $servie = Beans::get($this->getServiceBean());
            if ( $servie->count(array('pid' => $id, 'status' => 1)) > 0 ) {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '操作失败,请先禁用该分类所有的下级分类');
            }
            $brandService = Beans::get('product.brand.service');
            if ( $brandService->count(array('typeid' => $id, 'status' => 1)) > 0 ) {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '操作失败,请先禁用该分类下所有的品名');
            }
        }
        parent::set($request);
    }

    //批量启用|禁用
    public function enable(HttpRequest $request) {
        $value = $request->getParameter('value', 'trim');
        $ids = $request->getParameter('ids');
        if ( empty($ids) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $servie = Beans::get($this->getServiceBean());
        if ( $value == 0 ) {
            $brandService = Beans::get('product.brand.service');
            foreach ( $ids as $key => $val ) {
                if ( $servie->count(array('pid' => $val, 'status' => 1)) > 0 ) {
                    unset($ids[$key]);
                    continue;
                }
                if ( $brandService->count(array('typeid' => $val, 'status' => 1)) > 0 ) {
                    unset($ids[$key]);
                    continue;
                }
            }
            if ( count($ids) == 0 ) {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '所分类存在下级分类或拥有下属的品名，不允许禁用');
            }
        }
        if ( $servie->sets('status', $value, array('id' => array('$in' => $ids))) ) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }

    }

    public function delete(HttpRequest $request)
    {
        $id = $request->getParameter('id', 'intval');
        if ( $id == 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        //检查是否有子类
        $service = Beans::get($this->serviceBean);
        if ( $service->count(array('pid' => $id)) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '请先删除子类');
        }
        //检查是否有品名
        $brandService = Beans::get('product.brand.service');
        if ( $brandService->count(array('typeid' => $id)) > 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '该分类存在下属品名，不允许删除');
        }

        parent::delete($request);
    }

    //批量删除
    public function deletes(HttpRequest $request)
    {
        $ids = $request->getParameter('ids');
        if ( empty($ids) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        //检查是否有子类
        $service = Beans::get($this->serviceBean);
        $brandService = Beans::get('product.brand.service');
        foreach ( $ids as $key => $val ) {
            if ( $service->count(array('pid' => $val)) > 0
                || $brandService->count(array('typeid' => $val)) > 0 ) {
                unset($ids[$key]);
                continue;
            }
        }
        if ( $service->deletes(array('id' => array('$in' => $ids))) ) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    //导出数据
    protected function export(HttpRequest $request) {
        if( $request->getParameter('__export') == 1 ){
            $ids = $request->getParameter('ids');
            if( $ids ){
                $conditions['id']['$in']=$ids;
                $this -> setConditions($conditions);
            }
            $this->setPagesize(getConfig('export_max_count'));
            $service = Beans::get($this->getServiceBean());
            $items = $service->where($this->getConditions())->limit(1, $this->getPagesize())->sort(array('addtime' => -1))->find();
            $excel = array();
            foreach($items as $k => $v)
            {
                $tmp = array();
                $tmp[] = $v["name"];
                $tmp[] = $v["parent_name"] ? $v['parent_name'] : '顶级分类';
                $tmp[] = $v["subs_num"];
                $tmp[] = $v['status'] == 1 ? '启用' : '禁用';
                $excel[] = $tmp;
            }
            $header = $this->getTemplateVar('tableHeader');
            phpexcel("产品分类",$header,$excel);
            exit();
        }
    }
}
